package main

import (
	"database/sql"
	"fmt"

	_ "github.com/go-sql-driver/mysql"
)

func main() {
	driverName := "mysql"
	dsn := "golang:zxc,./123@tcp(43.139.115.142:3306)/user?charset=utf8mb4&loc=Local&parseTime=true"
	db, err := sql.Open(driverName, dsn)
	if err != nil {

		fmt.Println(err)
		return
	}
	defer db.Close()
	if err = db.Ping(); err != nil {
		fmt.Println(err)
		return
	}
	// 获取所有表
	sql := `
	show tables;
	`
	rows, err := db.Query(sql)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var tableName string
		// 获取表名
		err = rows.Scan(&tableName)
		if err != nil {
			fmt.Println(err)
			break
		}
		// 查看表信息
		sql = fmt.Sprintf("select * from %s", tableName)
		filedrows, err := db.Query(sql)
		if err != nil {
			fmt.Println(tableName, err)
		} else {
			// 获取字段信息  func (*sql.Rows).ColumnTypes() ([]*sql.ColumnType, error)
			// []*sql.ColumnType 字段信息
			columns, err := filedrows.ColumnTypes()
			if err != nil {
				fmt.Println(err)
			} else {
				fmt.Println("*****************")
				fmt.Println(tableName)
				for _, column := range columns {
					fmt.Println("\t", column.Name(), column.DatabaseTypeName())
				}
			}
		}

		filedrows.Close()
	}
}
